/*
 * @Date: 2020-09-11 10:45:59
 * @LastEditors: 小枫
 * @LastEditTime: 2020-09-25 20:13:20
 * @FilePath: \feng-blog\app\controller\Auth.ts
 */
import { Controller } from 'egg';

export default class AuthController extends Controller {
  public async index() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;
    // console.log(ctx.request.body);
    try {
      const isAuth = await ctx.service.auth.login(username, password);
      if (isAuth) {
        const token = await ctx.service.auth.createToken(username);
        ctx.status = 200;
        ctx.body = {
          token,
        };
        return;
      }
      ctx.status = 402;
      ctx.body = {
        msg: '账号或密码错误',
      };
    } catch (error) {
      console.log(error);
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }

  public async register() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;
    try {
      const hasUser = await ctx.service.auth.getUserById(username);
      if (hasUser === '') {
        console.log(hasUser);
        ctx.status = 403;
        ctx.body = {
          msg: '用户已存在',
        };
        return;
      }
      const result = await ctx.service.auth.createUser(username, password);
      ctx.status = 200;
      ctx.body = {
        data: result,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }

  public async getAllUser() {
    const { ctx } = this;
    const { page, limit } = ctx.request.query;
    const nLimit = limit ? parseInt(limit) : 10;
    const nPage = page ? parseInt(page) * nLimit : 0;
    try {
      const result = await ctx.service.auth.showAllUsers(nPage, nLimit);
      ctx.status = 200;
      ctx.body = {
        data: result,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }
}
